import axios from 'axios'
import qs from 'qs'
import cookie from 'js-cookie'

axios.defaults.baseURL = '/api'

// 在请求前在header中加入token
axios.interceptors.request.use(req => {
    let token = cookie.get('token')
    if (token) {
        req.headers.token = token
    }
    return req
}, err => {
    return Promise.reject(err)
})

// 判断token是否过期
axios.interceptors.response.use(res => {
    if (res.data.status === 401) {
        this.$message.error('token无效')
        cookie.remove('token')
        this.$router.push('/login')
    } else {
        return res
    }
}, err => {
    return Promise.reject(err)
})

const $http = {
    post: "",
    get: "",
}

$http.post = (url, data) => {
    if (!(data instanceof FormData)) {
        data = qs.stringify(data)
    }
    return new Promise(resolve => {
        axios.post(url, data).then(res => {
            resolve(res.data)
        }).catch(err => {
            resolve(err.response.data)
        })
    })
}

$http.get = (url, data) => {
    let query = qs.stringify(data)
    if (query) {
        query = "?" + query
    }
    return new Promise(resolve => {
        axios.get(url + query).then(res => {
            resolve(res.data)
        }).catch(err => {
            resolve(err.response.data)
        })
    })
}

export default $http